from flask import Blueprint, session, redirect, render_template, request
from utils import db

od = Blueprint("order", __name__)


@od.route("/order/list")
def order_list():
    status_dict = {1: "待执行", 2: "正在执行", 3: "完成", 4: "失败"}
    session_info = session.get("user_info")
    role = session_info["role"]  # 1-普通用户 2-管理员

    if role == 1:
        # select * from order where user_id = session_info['id]
        sql = "select * from `order` left join user_info on `order`.user_id = user_info.id where `order`.user_id = %s"
        parmars = [session_info["id"]]
        data_list = db.fetch_all(sql, parmars)

    else:
        # select * from order
        data_list = db.fetch_all(
            "select * from `order` left join user_info on `order`.user_id = user_info.id",
            [],
        )

    return render_template(
        "oder_list.html",
        data_list=data_list,
        status_dict=status_dict,
        real_name=session_info["real_name"],
    )


@od.route("/order/create", methods=["GET", "POST"])
def create_order():
    session_info = session.get("user_info")
    if request.method == "GET":
        return render_template("oder_create.html", real_name=session_info["real_name"])

    url = request.form.get("url")
    count = request.form.get("count")

    # 写入数据库,并返回最新ID
    order_id = db.insert(
        "insert into `order` (url, count, user_id, status) values (%s, %s, %s, 1)",
        [url, count, session_info["id"]]
    )
    # 写入redi
    print(f"写入redis队列: {order_id}")
    # cache.push_queque(order_id)

    return redirect("/order/list")

@od.route("/api/writer/role")
def writer_role():
    pass
